import 'dart:convert';

import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ylr_app/base/base_detail.dart';
import 'package:ylr_app/constants/constants.dart';
import 'package:ylr_app/utils/dio_util.dart';
import 'package:ylr_app/widget/home_news_more.dart';
import 'package:http/http.dart' as http;

/// 资讯
class HomeNews extends StatefulWidget {
  @override
  _HomeNewsState createState() => _HomeNewsState();
}

class _HomeNewsState extends State<HomeNews> {
  // http
  Future<NewsModel> fetchPost() async {
    final response =
        await http.get(Constants.BASE_URL + '/api/article/getArticleList');
    Utf8Decoder utf8decoder = Utf8Decoder(); //fix 中文乱码
    var result = json.decode(utf8decoder.convert(response.bodyBytes));
    return NewsModel.fromJson(result);
  }

  // dio
  Future<NewsModel> _getDataList() async {
    var result = await DioUtil.request('/api/article/getArticleList',
        method: DioUtil.GET);

    return NewsModel.fromJson(result);
  }

  Widget _listItemBuilder(item) {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.only(
          top: 10,
        ),
        height: ScreenUtil().setHeight(60),
        child: Flex(
          direction: Axis.horizontal,
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Expanded(
              flex: 1,
              child: Text(
                '${item.title}',
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Container(
              alignment: Alignment.centerRight,
              width: ScreenUtil().setWidth(260),
              child: item.updateTime != null
                  ? Text(formatDate(
                      DateTime.parse('${item.updateTime}'),
                      [yyyy, '-', mm, '-', dd],
                    ))
                  : Text(formatDate(
                      DateTime.parse('${item.createTime}'),
                      [yyyy, '-', mm, '-', dd],
                    )),
            ),
          ],
        ),
      ),
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => BaseDetail(
              contentTitle: '${item.title}',
              isShowVideo: false,
              id: int.parse('${item.id}'),
            ),
          ),
        );
      },
    );
  }

  Widget _createListView(BuildContext context, AsyncSnapshot snapshot) {
    if (snapshot.hasData) {
      //数据处理
      var data = snapshot.data;
      List<NewsItemModel> listData = (data.result as List).cast();

      return ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          NewsItemModel item = listData[index];

          return _listItemBuilder(item);
        },
        itemCount: listData.length,
      );
    }
  }

  Widget _buildFuture(BuildContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        return Text('还没开始网络请求');
      case ConnectionState.active:
        return Text('ConnectionState.active');
      case ConnectionState.waiting:
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        if (snapshot.hasError) return Text('Error: ${snapshot.error}');
        return _createListView(context, snapshot);
      default:
        return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(bottom: 5),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(5),
        border: Border.all(
          color: Color(Constants.border),
        ),
      ),
      child: Padding(
        padding: EdgeInsets.all(10),
        child: Column(
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/listbar.png'),
                  fit: BoxFit.fitWidth,
                ),
              ),
              child: Row(
                children: <Widget>[
                  Container(
                    width: ScreenUtil().setWidth(360),
                    margin: EdgeInsets.only(left: 10),
                    child: Text(
                      Constants.MODULE_HOME_NEWS,
                      style: TextStyle(
                        fontSize: Constants.font40,
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: GestureDetector(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: <Widget>[
                          Text(
                            Constants.MORE,
                            style: TextStyle(
                              fontSize: Constants.font30,
                            ),
                          ),
                          Icon(
                            Icons.arrow_forward_ios,
                            color: Colors.grey,
                            size: Constants.font36,
                          ),
                        ],
                      ),
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => HomeNewsMore(),
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
            FutureBuilder(
              builder: _buildFuture,
              future: _getDataList(),
            ),
          ],
        ),
      ),
    );
  }
}

// dart model
class NewsModel {
  int code;
  int timestamp;
  String message;
  bool success;
  List<NewsItemModel> result;

  NewsModel(
      {this.code, this.timestamp, this.message, this.success, this.result});

  factory NewsModel.fromJson(Map<String, dynamic> json) {
    final originList = json['result'] as List;

    List<NewsItemModel> newsItemModelList =
        originList.map((value) => NewsItemModel.fromJson(value)).toList();

    return NewsModel(
        code: json['code'],
        timestamp: json['timestamp'],
        message: json['message'],
        success: json['success'],
        result: newsItemModelList);
  }
}

class NewsItemModel {
  int id;
  String title;
  String createTime;
  String updateTime;

  NewsItemModel({this.id, this.title, this.createTime, this.updateTime});

  factory NewsItemModel.fromJson(Map<String, dynamic> json) {
    return NewsItemModel(
        id: json['id'],
        title: json['title'],
        createTime: json['createTime'],
        updateTime: json['updateTime']);
  }
}
